package com.rongxue.service.Impl;

import com.rongxue.mapper.*;
import com.rongxue.pojo.*;
import com.rongxue.rzzf.P2PXmlUtils;
import com.rongxue.service.CashInAndOutService;
import com.rongxue.service.shanbei.services.AccountService;
import com.rongxue.service.shanbei.util.ConfigUtil;
import com.rongxue.service.utils.P2PMessageUtils;
import com.rongxue.service.utils.RecordsUtils;
import com.rongxue.utils.CommonUtils;
import com.rongxue.utils.DateUtil;
import com.rongxue.utils.ExceptionUtils;
import com.alibaba.fastjson.JSONObject;
import com.rongxue.utils.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Service
@Transactional
public class CashInAndOutServiceImpl implements CashInAndOutService {

    private static final Logger LOG = LoggerFactory.getLogger(CashInAndOutServiceImpl.class);
    @Autowired
    private SUserMoneyRecordsMapper userMoneyRecordsMapper;
    @Autowired
    private SUserMapper userMapper;
    @Autowired
    private SUserBankMapper userBankMapper;
    @Autowired
    private SUserWalletRecordsMapper userWalletRecordsMapper;
    @Autowired
    private SUserAccountMapper userAccountMapper;
    @Autowired
    private SBankTypeMapper bankTypeMapper;
    @Autowired
    private SUserCashCouponMapper userCashCouponMapper;
    @Autowired
    private SInvestmentDetailMapper investmentDetailMapper;
    @Autowired
    private RecordsUtils recordsUtils;
    @Autowired
    private STelephonerateRechargeMapper sTelephonerateRechargeMapper;

    private static final Logger LOGGER = LoggerFactory.getLogger(CashInAndOutService.class);



    public static String MCHNT_CD = "0001000F0358674";//商户代码

    public static String KEY = "d8n0dh23w2yzrnez52ocqb4ckzp7t0fs" ;//密钥

//    public static String PAGE_NOTIFY_URL = "http://test.laoyeke.com:8080/laoyeke/";//商户回调地址



    public static String P2P_SEND_MSG_URL = "http://www-1.fuiou.com:18670/mobile_pay/";//认证支付url

    public static String APP_MCHNT_CD = "0001000F0358674";//APP商户代码

    public static String APP_KEY = "d8n0dh23w2yzrnez52ocqb4ckzp7t0fs";//APP商户密钥

    private static String mchnt_key = "d8n0dh23w2yzrnez52ocqb4ckzp7t0fs"; //富有秘钥

    private static String fuyou_code = "0001000F0358674"; //商户编号

//
    public static String SYS_URL = "http://app.laoyeke.com:8080/";//tomcat服务器地址

    public static String ADMIN_URL ="http://testadmin.laoyeke.com/";//测试后台

    public static String PAGE_NOTIFY_URL = "http://app.laoyeke.com:8080/test/";//测试商户回调地址

//    public static String ADMIN_URL ="http://admin_new.laoyeke.com";//后台地址
//
//    public static String PAGE_NOTIFY_URL = "http://app.laoyeke.com:8080/fudelong/";//商户回调地址

    public static BigDecimal FEE = new BigDecimal(2.00);//提现手续费

    public static ConcurrentHashMap<String, Long> map = new ConcurrentHashMap();


    //充值
    @Override
    public ObjectResult recharge(XMLBean xmlBean) {

        String userId =CommonUtils.decToken(xmlBean.getToken());
        SUser user = userMapper.selectUserInfoById(Long.parseLong(userId));
        if (user == null) {
            return ObjectResult.build("0", "用户信息有误");
        }
        if (1 != user.getCardNoAuth()) {
            return ObjectResult.build("0", "请先进行实名认证");
        }

        Long user_id = user.getId();
        String rechargeNo = new P2PMessageUtils().getRechargeNo("R");

        SUserBank sUserBank = userBankMapper.selectUserBankByUserId(userId);
        if (sUserBank == null){
            return ObjectResult.build("0", "银行卡信息错误");
        }

        //充值限额
        BigDecimal money = new BigDecimal(xmlBean.getMoney());
        BigDecimal quota = new BigDecimal(100);
        if (money.compareTo(quota) < 0 ){
            return ObjectResult.build("0", "充值金额不能低于"+quota+"元");
        }


        Map<String,Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("type",1);

        List<SUserWalletRecords> sUserWalletRecords = userWalletRecordsMapper.selectWalletRecordsByMap(map);

        String str = null;
        Map<String, Object> reqMap = new HashMap<String, Object>();
//        reqMap.put("service", "recharge_p");//快捷支付
        reqMap.put("service", "recharge_agreement_p");//协议支付
        reqMap.put("order_no", rechargeNo);
        reqMap.put("card_no", user.getCard_no2());
        reqMap.put("bind_card", sUserBank.getBankCardNo());
        reqMap.put("currency","156");
        reqMap.put("amount",money.setScale(2).toString());
        reqMap.put("fee","0.00");
        reqMap.put("cert_type","15");
        reqMap.put("cert_no",user.getCardNo());
        reqMap.put("name",user.getRealName());
        reqMap.put("mobile",sUserBank.getMobile());
//        reqMap.put("user_bank_code",sUserBank.getBankCode());
        reqMap.put("callback_url",PAGE_NOTIFY_URL+"tender/rechargeNotify");
        reqMap.put("client_ip", "47.98.107.188");
        reqMap.put("client_service", "00:16:3e:11:b0:02");
        if (sUserWalletRecords.size()>0){
            reqMap.put("auth_flag","N");
        }else {
            reqMap.put("auth_flag","y");

        }

        reqMap.put("success_url", PAGE_NOTIFY_URL+"index/resultHtml?type=1&title=1");
        reqMap.put("timestamp", String.valueOf(new Date().getTime() / 1000));
        reqMap.put("fail_url", PAGE_NOTIFY_URL+"index/resultHtml?type=0&title=2");
        reqMap.put("uuid", "" + System.currentTimeMillis() / 100);
        reqMap.put("sign_type", "MD5");
        reqMap.put("encode", "UTF-8");
        reqMap.put("version", "2.0.0");
        reqMap.put("custom", "");
        reqMap.put("client", "000001");
        reqMap.put("forget_pwd_url","http://apidata.rockfintech.com/doc/build/deposit.html");
        String rft_key = ConfigUtil.getPro("bank.key");
        String rft_secret = ConfigUtil.getPro("bank.secret");
        str = AccountService.createAccount(reqMap, rft_key, rft_secret);
        System.out.println(str.toString());

        JSONObject jsonObject = JSONObject.parseObject(str);



        //添加充值记录
        ObjectResult insertWalletRecordsResult = recordsUtils.insertWalletRecords(user_id, 1, new BigDecimal(xmlBean.getMoney()), rechargeNo,
                "用户充值", xmlBean.getDevice_type(), 2, sUserBank.getId(),jsonObject.getString("sequence_id"),jsonObject.getString("order_id"));

        if (insertWalletRecordsResult != null){
            return insertWalletRecordsResult;
        }

        if(!jsonObject.getString("code").equals("RD000000")){
            return  ObjectResult.build("0",jsonObject.getString("msg"));
        }

        return ObjectResult.build("1", "交易成功", jsonObject.getString("url"));

    }

    //提现
    @Override
    public ObjectResult withdrawDeposit(XMLBean xmlBean) {

        long time = System.currentTimeMillis();
        Long oldTime = map.put(xmlBean.getToken(), time);

        if (oldTime != null){
            if (time - oldTime < 3000){
                return ObjectResult.build("0", "请勿重复提交");
            }
        }

        String userId = CommonUtils.decToken(xmlBean.getToken());
        SUser user = userMapper.selectUserInfoById(Long.parseLong(userId));
        if (user == null) {
            return ObjectResult.build("0", "用户信息有误");
        }
        if (1 != user.getCardNoAuth()) {
            return ObjectResult.build("0", "请先进行实名认证");
        }

        //提现限额
        BigDecimal money = new BigDecimal(xmlBean.getMoney());
        BigDecimal quota = new BigDecimal(2);
//        if (money.compareTo(quota) < 0 ){
//            return ObjectResult.build("0", "提现金额不能低于"+quota+"元");
//        }

        //提现必须小于账户余额
        SUserAccount userAccount = this.userAccountMapper.selectUserAccountByUserId(user.getId());
        java.math.BigDecimal accountAble = userAccount.getAccount_able();
        if (accountAble.compareTo(money) < 0) {
            return com.rongxue.pojo.ObjectResult.build("0", "提现金额超过账户余额！");
        }

        SUserBank sUserBank = userBankMapper.selectUserBankByUserId(userId);
        if (sUserBank == null){
            return ObjectResult.build("0", "银行卡信息错误");
        }

        Long user_id = user.getId();
        String rechargeNo = new P2PMessageUtils().getRechargeNo("W");
        BigDecimal transAmount = new BigDecimal(0.00).subtract(money);


        String str = null;
        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("service","withdraw_p");
        reqMap.put("order_no",rechargeNo);
        reqMap.put("card_no",user.getCard_no2());//电子账户
        reqMap.put("bank_name",sUserBank.getBankName());//银行名称
        reqMap.put("bind_card",sUserBank.getBankCardNo());//	绑定卡号
        reqMap.put("name",sUserBank.getAcctName());//	姓名
        reqMap.put("cert_no",sUserBank.getIdNo());//证件号码
        if (user.getCardType()==2){
            reqMap.put("cert_type","25");//证件类型 , 必填，15-身份证18位，20-其它，25-企业社会信用代码 注：企业开户时上送20或社会信用号25 ,2(位数)
        }else {
            reqMap.put("cert_type","15");//证件类型 , 必填，15-身份证18位，20-其它，25-企业社会信用代码 注：企业开户时上送20或社会信用号25 ,2(位数)
        }
        reqMap.put("mobile",sUserBank.getMobile());//手机号码
        reqMap.put("amount",money.setScale(2).toString());//提现金额
        reqMap.put("fee",FEE.toString());//手续费
        reqMap.put("bank_city",sUserBank.getBankCity());//开户行城市,个人大额提现、企业/红包账户/手续费账户不论大小额提现必填
        reqMap.put("bank_province",sUserBank.getBankProvince());//开户行省份,个人大额提现、企业/红包账户/手续费账户不论大小额提现必填
        reqMap.put("callback_url",PAGE_NOTIFY_URL+"tender/withdraw_depositNotify");
        reqMap.put("success_url",  PAGE_NOTIFY_URL+"index/resultHtml?type=1&title=3");
        reqMap.put("sms_switch","1");
        reqMap.put("timestamp", String.valueOf(new Date().getTime() / 1000));
        reqMap.put("fail_url",  PAGE_NOTIFY_URL+"index/resultHtml?type=0&title=4");
        reqMap.put("uuid", "" + System.currentTimeMillis() / 100);
        reqMap.put("sign_type", "MD5");
        reqMap.put("encode", "UTF-8");
        reqMap.put("version", "2.0.0");
        reqMap.put("custom", "");
        reqMap.put("client", "000001");
        reqMap.put("forget_pwd_url","http://apidata.rockfintech.com/doc/build/deposit.html");
        reqMap.put("client_ip", "47.98.107.188");
        reqMap.put("client_service", "00:16:3e:11:b0:02");
        String rft_key = ConfigUtil.getPro("bank.key");
        String rft_secret = ConfigUtil.getPro("bank.secret");
        str = AccountService.createAccount(reqMap, rft_key, rft_secret);
        System.out.println(str.toString());

        JSONObject jsonObject = JSONObject.parseObject(str);


        //添加wallet成功记录
        recordsUtils.insertWalletRecords(user_id, 2, transAmount, rechargeNo, "用户提现", xmlBean.getDevice_type(), 3, sUserBank.getId(),jsonObject.getString("sequence_id"),jsonObject.getString("order_id"));

        if(!jsonObject.getString("code").equals("RD000000")){
            return  ObjectResult.build("0",jsonObject.getString("msg"));
        }

        return ObjectResult.build("1", "提现成功",jsonObject.getString("url"));
    }


    //充值回调
    @Override
    public ObjectResult verificationrechargeNotify(JSONObject jsonObject) {

        SUserWalletRecords sUserWalletRecords = userWalletRecordsMapper.selectWalletRecordsByrRechargeNo(jsonObject.getString("order_no"));
        //返回数据验证
        if (sUserWalletRecords != null) {
            if (new BigDecimal(jsonObject.getString("amount")).compareTo(sUserWalletRecords.getValue()) == 0) {

                //防止返回重复成功回调,重复添加记录
                SUserWalletRecords sUserWalletRecordsResult = userWalletRecordsMapper.selectWalletRecordsByrRechargeNo(jsonObject.getString("order_no"));
                if (sUserWalletRecordsResult.getPayStatus() == 2) {
                    return ObjectResult.build("0", "重复记录");
                }

                //更改账户余额,修改wallet成功,添加成功记录
                Long userId = null;
                try {
                    //保存返回码
                    userId = sUserWalletRecords.getUser_id();
                    BigDecimal value = sUserWalletRecords.getValue();

                    recordsUtils.saveCodeByTradeNo(sUserWalletRecordsResult.getTradeNo(), jsonObject.getString("code")+ jsonObject.getString("msg"));

                    SUserMoneyRecords moneyRecords = new SUserMoneyRecords();
                    moneyRecords.setUserId(userId);
                    moneyRecords.setValue(value);
                    moneyRecords.setDescr("用户充值");
                    moneyRecords.setType(108);
                    moneyRecords.setStatus(1);
                    moneyRecords.setAddTime(new Date());
                    userMoneyRecordsMapper.insert(moneyRecords);

                    //设置银行卡已支付
                    SUserBank userBank = new SUserBank();
                    userBank.setUserId(sUserWalletRecords.getUser_id());
                    userBank.setModifyTime(new Date());
                    userBank.setHasPaySuccess(2);
                    userBankMapper.updateByUserId(userBank);

                    recordsUtils.updateAccountAble(userId, value);
                    //修改充值提现记录表 设置为支付或者提现成功
                    userWalletRecordsMapper.updateStatusByRefnumber("2", sUserWalletRecords.getRecharge_no());

                    SUser resultUser = userMapper.selectUserInfoById(userId);
                    //发送短信验证码
//                    HashMap<String, String> hashMap = new HashMap<>();
//                    hashMap.put("mobile", resultUser.getMobile());
////                    hashMap.put("mobile", "13758876025");
//                    hashMap.put("tpl_id", "92420");
//                    hashMap.put("key", MobileCodeServiceImpl.SMS_KEY);
//                    hashMap.put("tpl_value", "#name#="+resultUser.getRealName()+"&#time#="+DateUtil.formatDateTime()+"&#money#="+value);
//                    ObjectResult objectResult2 = HttpClientUtil.verificationOfBankCard(MobileCodeServiceImpl.SMS_URL, hashMap);


                    return ObjectResult.build("1", "交易成功");
                } catch (Exception e) {
                    ExceptionUtils.recordException(true, "用户:"+userId+",TransAmt:"+jsonObject.getString("amount")+",OrdId:"+jsonObject.getString("order_no")+",充值回调,保存成功记录,发生异常", "", e);
                    return ObjectResult.build("0", "服务器异常0x06,请联系客服处理");
                }

            } else {
                return ObjectResult.build("0", "验签失败0x08");
            }

        }else {
            return ObjectResult.build("0", "不存在的充值记录");
        }
    }

    @Override
    public ObjectResult withdraw_depositNotify(JSONObject jsonObject) {
        SUserWalletRecords sUserWalletRecords1 = userWalletRecordsMapper.selectWalletRecordsByrRechargeNo(jsonObject.getString("order_no"));
        if((new BigDecimal(0).subtract(sUserWalletRecords1.getValue())).compareTo(new BigDecimal(jsonObject.getString("amount")))!=0){
            return ObjectResult.build("0","金额不匹配提现失败");
        }
        if (sUserWalletRecords1.getPayStatus()==2){
            return ObjectResult.build("0","重复的回调");
        }

        SUserWalletRecords sUserWalletRecords = new SUserWalletRecords();
        sUserWalletRecords.setPayStatus(2);
        sUserWalletRecords.setStatus(1);
        sUserWalletRecords.setModifyTime(new Date());
        sUserWalletRecords.setRecharge_no(sUserWalletRecords1.getRecharge_no());
        sUserWalletRecords.setUser_id(sUserWalletRecords1.getUser_id());
        //修改提现记录为成功
        userWalletRecordsMapper.updateSelective(sUserWalletRecords);

        //添加成功记录
        ObjectResult saveCashAndOutRecordsResult = recordsUtils.saveCashAndOutRecords(sUserWalletRecords1.getUser_id(), sUserWalletRecords1.getValue(), "用户提现", 2, sUserWalletRecords1.getRecharge_no() , 3);
        if (saveCashAndOutRecordsResult != null){
            return saveCashAndOutRecordsResult;
        }

        //更改账户余额
        ObjectResult updateAccountAbleResult = recordsUtils.updateAccountAble(sUserWalletRecords1.getUser_id(), sUserWalletRecords1.getValue());
        if (updateAccountAbleResult != null){
            return updateAccountAbleResult;
        }

        SUser resultUser = userMapper.selectUserInfoById(sUserWalletRecords1.getUser_id());
        //发送短信验证码
//        HashMap<String, String> hashMap = new HashMap<>();
//        hashMap.put("mobile", resultUser.getMobile());
////        hashMap.put("mobile", "13758876025");
//        hashMap.put("tpl_id", "92425");
//        hashMap.put("key", MobileCodeServiceImpl.SMS_KEY);
//        hashMap.put("tpl_value", "#name#="+resultUser.getRealName()+"&#time#="+DateUtil.formatDateTime()+"&#money#="+xmlBean.getTransAmt());
//        ObjectResult objectResult2 = HttpClientUtil.verificationOfBankCard(MobileCodeServiceImpl.SMS_URL, hashMap);


        return ObjectResult.build("1","提现成功");
    }

    //绑卡
    @Override
    public ObjectResult bindingBankNo(XMLBean xmlBean) {

        String userId = CommonUtils.decToken(xmlBean.getToken());
        P2PMessageUtils p2PMessageUtils = new P2PMessageUtils();
        SUser resultUser =userMapper.selectUserInfoById(Long.parseLong(userId));
        if (resultUser == null){
            return ObjectResult.build("0", "用户信息错误,请重试");
        }

        if (resultUser.getCardNoAuth() == 1){
            return ObjectResult.build("0", "您已绑定身份证");
        }

        //查询身份证是否被绑定
        SUser user = this.userMapper.selectUserIdByIdAndCardNo(xmlBean.getCard_no());
        if (user != null) {
                return ObjectResult.build("0", "该身份证已被绑定");
        }

        SUserBank sUserBank = userBankMapper.selectUserBankByUserId(userId);
        if (sUserBank != null){
            return ObjectResult.build("0", "您已绑定银行卡");
        }

        String requestReferenceID = P2PXmlUtils.getRequestReferenceID();
        String data = "1.0" + "|" + "NN" + "|" + MCHNT_CD + "|" + requestReferenceID + "|" + xmlBean.getReal_name() + "|" + xmlBean.getCard_no() + "|" + KEY;
        LOGGER.info("====签名明文===="+data);
        String sign = p2PMessageUtils.getMD5(data);
        if (sign == null || sign.equals("")) {
            LOGGER.error("获取sign失败");
            return ObjectResult.build("0", "服务器错误0x01,请重试");
        }
        LOGGER.info("====签名密文===="+sign);

        //拼接报文
        StringBuffer sb = new StringBuffer();
        sb.append("<ORDER><VERSION>1.0</VERSION>");
        sb.append("<TYPEID>NN</TYPEID>");
        sb.append("<MCHNTCD>" + MCHNT_CD + "</MCHNTCD>");
        sb.append("<MCHNTORDERID>" + requestReferenceID + "</MCHNTORDERID>");
        sb.append("<NAME>" + xmlBean.getReal_name() + "</NAME>");
        sb.append("<IDNO>" + xmlBean.getCard_no() + "</IDNO>");
        sb.append("<REM1></REM1><REM2></REM2><REM3></REM3>");
        sb.append("<SIGN>" + sign + "</SIGN></ORDER>");

        //获取返回结果
        ObjectResult result = p2PMessageUtils.getDecXml(P2P_SEND_MSG_URL + "checkInfo/checkIdentity.pay", sb.toString(), 1);

       if (result.getData() != null && result.getCode().equals("1")) {
            Map<String, String> xmlElementMap = (Map<String, String>) result.getData();
            //身份证认证成功
            if (xmlElementMap.get("MCHNTORDERID").equals(requestReferenceID)) {

                //验证银行卡
                //生成sign
                String bankRequestReferenceID = P2PXmlUtils.getRequestReferenceID();
                String bankData = MCHNT_CD + "|1.30|" + bankRequestReferenceID + "|" + xmlBean.getBank_no() + "|0|" + xmlBean.getCard_no() + "|" + KEY;
                String bankSign = p2PMessageUtils.getMD5(bankData);
                if (bankSign == null || bankSign.equals("")) {
                    LOGGER.error("获取sign失败");
                    return ObjectResult.build("0", "服务器错误0x01,请重试");
                }
                LOGGER.info("=====签名明文===="+bankData);
                LOGGER.info("=====签名密文===="+bankSign);
                //拼接报文
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append("<FM>");
                stringBuffer.append("<MchntCd>" + MCHNT_CD + "</MchntCd>");
                stringBuffer.append("<Ono>" + xmlBean.getBank_no() + "</Ono>");
                stringBuffer.append("<Onm>" + xmlBean.getReal_name() + "</Onm>");
                stringBuffer.append("<OCerTp>0</OCerTp>");
                stringBuffer.append("<OCerNo>" + xmlBean.getCard_no() + "</OCerNo>");
                stringBuffer.append("<Mno>" + xmlBean.getMobile() + "</Mno>");
                stringBuffer.append("<Sign>" + bankSign + "</Sign>");
                stringBuffer.append("<Ver>1.30</Ver>");
                stringBuffer.append("<OSsn>" + bankRequestReferenceID + "</OSsn>");
                stringBuffer.append("</FM>");

                //获取返回结果
                ObjectResult bankResult = p2PMessageUtils.getDecXml(P2P_SEND_MSG_URL + "checkCard/checkCardDebit.pay ", stringBuffer.toString(), 2);

                if (bankResult.getData() != null && bankResult.getCode().equals("1")) {

                    Map<String, String> bankXmlElementMap = (Map<String, String>) bankResult.getData();
                    //银行卡验证成功
                    if (bankXmlElementMap.get("OSsn").equals(bankRequestReferenceID) && bankXmlElementMap.get("CardNo").equals(xmlBean.getBank_no())
                            && bankXmlElementMap.get("MchntCd").equals(MCHNT_CD)) {

                        try {
                            //更新数据库
                            resultUser.setRealNameAuth(1);
                            resultUser.setCardNoAuth(1);
                            resultUser.setCardNo(xmlBean.getCard_no());
                            resultUser.setRealName(xmlBean.getReal_name());
                            resultUser.setCardType(1);
                            userMapper.updateByPrimaryKeySelective(resultUser);

                            Long user_Id = resultUser.getId();
                            //更新数据库
                            SUserBank bank = new SUserBank();
                            bank.setUserId(user_Id);//用户id
                            bank.setBankName(bankXmlElementMap.get("Cnm"));//发卡银行名称
                            bank.setPayType("10");//默认是快捷支付（借记卡）
                            bank.setBankCode(bankXmlElementMap.get("InsCd"));//银行编号
                            bank.setIdType(1);//身份证或者是其他
                            bank.setMobile(xmlBean.getMobile());//卡的手机号
                            bank.setIdNo(xmlBean.getCard_no());//身份证号
                            bank.setAcctName(xmlBean.getReal_name());//该卡归属人姓名
                            bank.setPayChannel(Integer.valueOf(1));//支付渠道---连连支付
                            bank.setIsDeleted(Integer.valueOf(0));//默认是解绑状态等 银行绑定成功该变该值
                            bank.setBankCardNo(bankXmlElementMap.get("CardNo"));//银行卡号
                            bank.setHasPaySuccess(Integer.valueOf(1));//是否成功支付过---1未支付成功,2支付成功
                            bank.setAddTime(new Date());//添加日期
                            bank.setAddUserId(user_Id);//添加人
                            bank.setModifyTime(new Date());
                            bank.setModifyUserId(user_Id);
                            userBankMapper.insertSelective(bank);
                        } catch (Exception e) {
                            ExceptionUtils.recordException(true, "用户:"+user.getMobile()+"绑卡,保存成功记录操作数据库,发生异常", "", e);
                            return ObjectResult.build("0", "服务器异常0x06,请联系客服处理");
                        }

                        return ObjectResult.build("1", "绑卡成功");

                    }else {
                        return ObjectResult.build("0", "验证银行卡失败" + bankXmlElementMap.get("RDesc"));
                    }

                }else {
                    return bankResult;
                }


            }else {
                return ObjectResult.build("0", "验证身份证失败" + xmlElementMap.get("RESPONSEMSG"));
            }

        }else {
            return result;
        }
    }

    @Override
    public ObjectResult telephonerateRecharge(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        P2PMessageUtils p2PMessageUtils = new P2PMessageUtils();
        SUser resultUser =userMapper.selectUserInfoById(Long.parseLong(userId));

        STelephonerateRecharge sTelephonerateRecharge = new STelephonerateRecharge();
        sTelephonerateRecharge.setUser_id(Long.parseLong(userId));
        sTelephonerateRecharge.setMobile(xmlBean.getMobile());
        sTelephonerateRecharge.setReal_value(new BigDecimal(xmlBean.getReal_value()));
        sTelephonerateRecharge.setValue(new BigDecimal(xmlBean.getValue()));
        sTelephonerateRecharge.setAdd_time(new Date());
        sTelephonerateRecharge.setStatus(0);

        sTelephonerateRechargeMapper.insert(sTelephonerateRecharge);


        //更改账户余额
        ObjectResult updateAccountAbleResult = recordsUtils.updateAccountAble(Long.parseLong(userId), new BigDecimal(0).subtract(new BigDecimal(xmlBean.getValue())));
        if (updateAccountAbleResult != null){
            return updateAccountAbleResult;
        }

        return ObjectResult.build("1","充值成功");
    }

    @Override
    public ObjectResult updatapassword(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        P2PMessageUtils p2PMessageUtils = new P2PMessageUtils();
        SUser resultUser =userMapper.selectUserInfoById(Long.parseLong(userId));
        String rechargeNo = p2PMessageUtils.getRechargeNo("K");

        String str = null;
        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("service", "set_password_p");
        reqMap.put("customer_no",resultUser.getCustomer_no());
        reqMap.put("card_no",resultUser.getCard_no2());
        reqMap.put("out_serial_no", rechargeNo);
        reqMap.put("callback_url", CashInAndOutServiceImpl.PAGE_NOTIFY_URL+"tender/updataPasswordNotify");
        reqMap.put("success_url", "https://www.rockfintech.com");
        reqMap.put("timestamp", String.valueOf(new Date().getTime() / 1000));
        reqMap.put("fail_url", "http://apidata.rockfintech.com/doc/build/deposit.html");
        reqMap.put("uuid", "" + System.currentTimeMillis() / 100);
        reqMap.put("sign_type", "");
        reqMap.put("encode", "UTF-8");
        reqMap.put("version", "2.0.0");
        reqMap.put("custom", "");
        reqMap.put("client", "000001");
        reqMap.put("risk_level_flag", "1");
        reqMap.put("client_ip", "47.98.107.188");
        reqMap.put("client_service", "00:16:3e:11:b0:02");
        String rft_key = ConfigUtil.getPro("bank.key");
        String rft_secret = ConfigUtil.getPro("bank.secret");
        str = AccountService.createAccount(reqMap, rft_key, rft_secret);
        System.out.println(str.toString());
        JSONObject jsonObject = JSONObject.parseObject(str);
        if(!jsonObject.getString("code").equals("RD000000")){
            return  ObjectResult.build("0",jsonObject.getString("msg"));
        }
        return ObjectResult.build("1","成功",jsonObject.getString("url"));
    }

    @Override
    public ObjectResult signBorrower(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        P2PMessageUtils p2PMessageUtils = new P2PMessageUtils();
        SUser resultUser =userMapper.selectUserInfoById(Long.parseLong(userId));
        String rechargeNo = p2PMessageUtils.getRechargeNo("S");

        String startTime = (new Date().getTime()/1000)+"";
        String endTime = (DateUtil.addDateDay(new Date(),365).getTime()/1000) +"";

        String str = null;
        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("service", "sign_borrower_p");
        reqMap.put("card_no",resultUser.getCard_no2());//电子账户
        reqMap.put("payment_amount","1000000.00");//放款手续费签约金额
        reqMap.put("repayment_amount", "1000000.00");//还款签约金额, 手续费+ 利息 + 还款金额
        reqMap.put("out_serial_no",rechargeNo);
        reqMap.put("payment_start_time",startTime);//放款手续费签约开始时间
        reqMap.put("repayment_start_time",startTime);//还款签约开始时间
        reqMap.put("payment_end_time",endTime);//放款手续费签约结束时间
        reqMap.put("repayment_end_time",endTime);//还款签约结束时间
        reqMap.put("callback_url", PAGE_NOTIFY_URL+"tender/signBorrowerNotify");
        reqMap.put("success_url", PAGE_NOTIFY_URL+"index/resultHtml?type=1&title=9");
        reqMap.put("forget_pwd_url","https://www.rockfintech.com");
        reqMap.put("timestamp", String.valueOf(new Date().getTime() / 1000));
        reqMap.put("fail_url", PAGE_NOTIFY_URL+"index/resultHtml?type=0&title=10");
        reqMap.put("uuid", "" + System.currentTimeMillis() / 100);
        reqMap.put("sign_type", "");
        reqMap.put("encode", "UTF-8");
        reqMap.put("version", "2.0.0");
        reqMap.put("custom", "");
        reqMap.put("client", "000002");
        reqMap.put("risk_level_flag", "1");
        reqMap.put("client_ip", "47.98.107.188");
        reqMap.put("client_service", "00:16:3e:11:b0:02");
        String rft_key = ConfigUtil.getPro("bank.key");
        String rft_secret = ConfigUtil.getPro("bank.secret");
        str = AccountService.createAccount(reqMap, rft_key, rft_secret);
        System.out.println(str.toString());
        JSONObject jsonObject = JSONObject.parseObject(str);
        if(!jsonObject.getString("code").equals("RD000000")){
            return  ObjectResult.build("0",jsonObject.getString("msg"));
        }


        SUser sUser = new SUser();
        sUser.setId(Long.parseLong(userId));
        sUser.setOut_serial_no(rechargeNo);
        sUser.setSequence_id(jsonObject.getString("sequence_id"));
        userMapper.updateByPrimaryKeySelective(sUser);


        return ObjectResult.build("1","成功",jsonObject.getString("url"));
    }

    @Override
    public ObjectResult revokeRepayment(XMLBean xmlBean) {
        String userId = "103";//CommonUtils.decToken(xmlBean.getToken());
        P2PMessageUtils p2PMessageUtils = new P2PMessageUtils();
        SUser resultUser =userMapper.selectUserInfoById(Long.parseLong(userId));
        String rechargeNo = p2PMessageUtils.getRechargeNo("R");

        String startTime = (new Date().getTime()/1000)+"";
        String endTime = (DateUtil.addDateDay(new Date(),365).getTime()/1000) +"";


        String str = null;
        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("service", "revoke_repayment");
        reqMap.put("card_no",resultUser.getCard_no2());//电子账户
        reqMap.put("out_serial_no",rechargeNo);
        reqMap.put("origin_serial_no",resultUser.getOut_serial_no());
        reqMap.put("timestamp", String.valueOf(new Date().getTime() / 1000));
        reqMap.put("uuid", "" + System.currentTimeMillis() / 100);
        reqMap.put("sign_type", "");
        reqMap.put("encode", "UTF-8");
        reqMap.put("version", "2.0.0");
        reqMap.put("custom", "");
        reqMap.put("client", "000001");
        reqMap.put("client_ip", "47.98.107.188");
        reqMap.put("client_service", "00:16:3e:11:b0:02");
        String rft_key = ConfigUtil.getPro("bank.key");
        String rft_secret = ConfigUtil.getPro("bank.secret");
        str = AccountService.createAccount(reqMap, rft_key, rft_secret);
        System.out.println(str.toString());
        JSONObject jsonObject = JSONObject.parseObject(str);

        return ObjectResult.build("1","成功",jsonObject);
    }

    @Override
    public ObjectResult signAgain(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        P2PMessageUtils p2PMessageUtils = new P2PMessageUtils();
        SUser resultUser =userMapper.selectUserInfoById(Long.parseLong(userId));
        String rechargeNo = p2PMessageUtils.getRechargeNo("A");

        String startTime = (new Date().getTime()/1000)+"";
        String endTime = (DateUtil.addDateDay(new Date(),365).getTime()/1000) +"";


        String str = null;
        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("service", "sign_again_p");
        reqMap.put("card_no",resultUser.getCard_no2());//电子账户
        reqMap.put("out_serial_no",rechargeNo);
        reqMap.put("origin_serial_no",resultUser.getOut_serial_no());
        reqMap.put("interface_type","repayment");//自动债权转让签约trans、投资人自动投标签约 bid、转让方转让手续费签约transfer、放款手续费签约payment、借款人还款金额签约repayment
        reqMap.put("amount", "1000000.00");//最大签约金额
        reqMap.put("start_time",startTime);
        reqMap.put("end_time",endTime);
        reqMap.put("callback_url", PAGE_NOTIFY_URL+"tender/signAgainNotify");
        reqMap.put("success_url", PAGE_NOTIFY_URL+"index/resultHtml?type=1&title=9");
        reqMap.put("forget_pwd_url","https://www.rockfintech.com");
        reqMap.put("timestamp", String.valueOf(new Date().getTime() / 1000));
        reqMap.put("fail_url", PAGE_NOTIFY_URL+"index/resultHtml?type=0&title=10");
        reqMap.put("uuid", "" + System.currentTimeMillis() / 100);
        reqMap.put("sign_type", "");
        reqMap.put("encode", "UTF-8");
        reqMap.put("version", "2.0.0");
        reqMap.put("custom", "");
        reqMap.put("client", "000001");
        reqMap.put("client_ip", "47.98.107.188");
        reqMap.put("client_service", "00:16:3e:11:b0:02");
        String rft_key = ConfigUtil.getPro("bank.key");
        String rft_secret = ConfigUtil.getPro("bank.secret");
        str = AccountService.createAccount(reqMap, rft_key, rft_secret);
        System.out.println(str.toString());
        JSONObject jsonObject = JSONObject.parseObject(str);
        if(!jsonObject.getString("code").equals("RD000000")){
            return  ObjectResult.build("0",jsonObject.getString("msg"));
        }

        return ObjectResult.build("1","成功",jsonObject.getString("url"));
    }
}
